package com.base.test.mutual.utils;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.crypto.PemUtil;
import com.base.commons.tools.utils.HttpConnectUtil;
import com.base.commons.tools.utils.RSAUtils;
import com.base.test.mutual.properties.UicProperties;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;

import java.security.PrivateKey;
import java.util.HashMap;

@Log4j2
//@Configuration
//@EnableConfigurationProperties(UicProperties.class)
public class UicHttpUtils {

    @Autowired
    private UicProperties uicProperties;

    public  <T> T execute(T requestObj, String url,String method, Class<?> clazz){
        ResponseEntity res=null;
        try {
            url=uicProperties.getUrl()+url;
            HttpHeaders headers = new HttpHeaders();
            String appSecret=uicProperties.getAppSecret();
            String version=uicProperties.getVersion();
            String timestamp= DateUtil.now();
            String  data="appSecret="+appSecret+"&charset=UTF-8&timestamp="+timestamp+"&version="+version;
            PrivateKey privateKey= PemUtil.readPemPrivateKey(new ClassPathResource(uicProperties.getPathPrivateKey()).getStream());
            String sign= RSAUtils.signHtool(data,privateKey);
            headers.add("appSecret",appSecret);//密钥
            headers.add("timestamp",timestamp);
            headers.add("charset","UTF-8");
            headers.add("version",version);
            headers.add("sign",sign);
            log.info("模块Module:{},url:{},请求参数[{}],请求结果：{}","Uic",url,requestObj);
            res = HttpConnectUtil.tempHttp(requestObj, url, headers, method, new HashMap<>(), clazz);
            log.info("模块Module:{},url:{},请求结果：{}","Uic",url,res.getBody());
        }catch (Exception e) {
            log.error("模块Module:{},url:{},请求参数[{}],异常信息：{}","Uic",url,requestObj,e);
        }
        return (T) res.getBody();
    }
}
